package com.qiaofang.applet.filter;

import com.qiaofang.applet.common.constant.CommonConstant;
import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.common.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 刷新token过期时间
 * @author QF2019
 */
//@Component
public class RefreshTokenFilter extends GenericFilterBean {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String token = ((HttpServletRequest) servletRequest).getHeader(CommonConstant.HEADER_TOKEN);
        if(StringUtils.isNotEmpty(token) && redisUtil.hasKey(RedisKeyUtil.getWebTokenKey(token))) {
            // 刷新token过期时间
            redisUtil.expire(RedisKeyUtil.getWebTokenKey(token), CommonConstant.TOKEN_TIMEOUT, TimeUnit.MILLISECONDS);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
